/**
 *
 * 2007-11-3 上午10:43:46
 * @author xuhuan
 */

package edu.ccut.saturn.studio.logic.parts;

import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;

import org.eclipse.draw2d.IFigure;
import org.eclipse.draw2d.PolygonDecoration;
import org.eclipse.draw2d.PolylineConnection;
import org.eclipse.gef.EditPolicy;
import org.eclipse.gef.commands.Command;
import org.eclipse.gef.editparts.AbstractConnectionEditPart;
import org.eclipse.gef.editpolicies.ConnectionEditPolicy;
import org.eclipse.gef.editpolicies.ConnectionEndpointEditPolicy;
import org.eclipse.gef.requests.GroupRequest;
import org.eclipse.swt.graphics.Color;

import edu.ccut.saturn.studio.logic.model.BasicShape;
import edu.ccut.saturn.studio.logic.model.commands.ConnectionDeleteCommand;
import edu.ccut.saturn.studio.logic.model.saturn.SaturnFalseConnection;

public class SaturnFalseConnectionEditPart extends AbstractConnectionEditPart
		implements PropertyChangeListener {

	public void activate() {
		if (!isActive()) {
			super.activate();
			((BasicShape) getModel()).addPropertyChangeListener(this);
		}
	}

	protected void createEditPolicies() {
		installEditPolicy(EditPolicy.CONNECTION_ENDPOINTS_ROLE,
				new ConnectionEndpointEditPolicy());
		installEditPolicy(EditPolicy.CONNECTION_ROLE,
				new ConnectionEditPolicy() {
					protected Command getDeleteCommand(GroupRequest request) {
						return new ConnectionDeleteCommand(getCastedModel());
					}
				});
	}

	protected IFigure createFigure() {
		PolylineConnection connection = (PolylineConnection) createFigure();
		connection.setTargetDecoration(new PolygonDecoration()); // arrow at
		connection.setLineStyle(getCastedModel().getLineStyle()); // line
		connection.setBackgroundColor(new Color(null, 255, 29, 33)); // drawing
		return connection;
	}

	/**
	 * Upon deactivation, detach from the model element as a property change
	 * listener.
	 */
	public void deactivate() {
		if (isActive()) {
			super.deactivate();
			((BasicShape) getModel()).removePropertyChangeListener(this);
		}
	}

	private SaturnFalseConnection getCastedModel() {
		return (SaturnFalseConnection) getModel();
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see java.beans.PropertyChangeListener#propertyChange(java.beans.PropertyChangeEvent)
	 */
	public void propertyChange(PropertyChangeEvent event) {
		String property = event.getPropertyName();
		if (SaturnFalseConnection.LINESTYLE_PROP.equals(property)) {
			((PolylineConnection) getFigure()).setLineStyle(getCastedModel()
					.getLineStyle());
		}
	}

}
